#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>
static int num = 1;
class Thread
{
    // 回调函数
    using func_t = std::function<void()>;

public:
    Thread(func_t func)
        : _tid(-1), isrunning(false), isdetach(false), _func(func)
    {
        _name += "Thread-" + std::to_string(num++);
    }
    void EnableDetach()
    {
        isdetach = true;
    }
    void EnableRunning()
    {
        isrunning = true;
    }
    void Start()
    {
        if (isrunning)
        {
            return;
        }
        int ret = pthread_create(&_tid, nullptr, Routine, this);
    }
    // 分离线程
    void Datech()
    {
        if (isdetach)
        {
            int ret = pthread_detach(_tid);
            (void)ret;
        }
        else
        {
            return;
        }
    }
    ~Thread()
    {
    }
    //终止线程:
    bool Stop()
    {
        if(isrunning)
        {
            int ret=pthread_cancel(_tid);
            if(ret==0)
            {
                isrunning=false;
                return true;
            }
            else
            {
                return false;
            }
        }
        return false;
    }
    //线程等待：
    void join()
    {
        if(isdetach)
        {
            return ;
        }
        pthread_join(_tid,nullptr);
    }
private:
    static void *Routine(void *args)
    {
        Thread *self = static_cast<Thread *>(args);
        self->EnableRunning();
        if (self->isdetach)
        {
            self->Datech();
        }
        int n = pthread_setname_np(self->_tid, self->_name.c_str());
        (void)n;
        // 调用回调函数：
        self->_func();
        return nullptr;
    }
    std::string _name;
    bool isrunning;
    bool isdetach;
    func_t _func;
    pthread_t _tid;
};